package tools;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;

import core.DrawContext;
import core.DrawTool;
import core.VectorialObject;


public class PencilTool extends DrawTool {
	
	private Point2D.Double lastPointDrawn = null;
	
	private Color color = Color.black;
	
	private Cursor cursor = Cursor.getDefaultCursor();
	
	private int size = 1;
	
	public void processKeyEvent(KeyEvent evt, DrawContext context) {
		// TODO Auto-generated method stub

	}

	public void processMouseEvent(MouseEvent evt, DrawContext context) {
		
		switch(evt.getID()){
		case MouseEvent.MOUSE_DRAGGED:
		case MouseEvent.MOUSE_PRESSED:
			draw(evt, context);
			break;
		case MouseEvent.MOUSE_RELEASED:
			processRealease();
			break;
		case MouseEvent.MOUSE_MOVED:
			configureMouseIcon(evt, context, cursor);
		}
		
	}

	public Cursor getCursor() {
		return cursor;
	}

	public void setCursor(Cursor cursor) {
		this.cursor = cursor;
	}

	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}


	
	private void draw(MouseEvent evt, DrawContext ctx){
		
		drawPoint(evt.getX(), evt.getY(), ctx.getGraphics().getRealGraphics());
		
		//Interpolates
		if(lastPointDrawn != null){
			interpolate(evt.getX(), evt.getY(), ctx.getGraphics().getRealGraphics());
		}else{
			lastPointDrawn = new Point2D.Double();
		}
		
		lastPointDrawn.x = evt.getX();
		lastPointDrawn.y = evt.getY();
		
		ctx.setChanged(true);
	}
	
	private void drawPoint(int x, int y, Graphics2D g){
		
		g.setColor(this.color);
		
		g.fillRect(x, y, size, size);	
	}
	
	private void interpolate(int x, int y, Graphics2D g){
		
		double dx = (double)(x - lastPointDrawn.x);
		double dy = (double)(y - lastPointDrawn.y);
		
		int interCount = (int) Math.max(Math.abs(dx), Math.abs(dy));
		
		double xi = lastPointDrawn.x;
		
		double yi = lastPointDrawn.y;
		
		for(int i = 0; i < interCount; i++){
			
			xi += dx/(double)interCount;
			yi += dy/(double)interCount;
			
			drawPoint((int)xi, (int)yi, g);
		}
	}
	
	private void processRealease(){
		lastPointDrawn = null;
	}

	@Override
	public void dispose(DrawContext ctx) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(DrawContext ctx) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSelection(VectorialObject vo) {
		// TODO Auto-generated method stub
		
	}

}
